import request from '../utls/require'

const requestFirstSuccess = async (attempts: Array<{ url: string; method: 'get'|'post'|'patch'|'put'|'delete'; data?: any; params?: any }>) => {
  for (const cfg of attempts) {
    try {
      const resp = await request({ url: cfg.url, method: cfg.method, data: cfg.data, params: cfg.params })
      return resp
    } catch (e: any) {
      const status = e?.response?.status
      if (status === 404 || status === 405) continue
      throw e
    }
  }
  throw new Error('All endpoints failed')
}

const getTasksEndpointsConfig = () => {
  try {
    const raw = localStorage.getItem('tasksEndpoints')
    if (!raw) return {}
    const obj = JSON.parse(raw)
    return typeof obj === 'object' && obj ? obj : {}
  } catch { return {} }
}

// 定义请求和响应的类型
interface UpdateUserInfoData {
  nickname?: string
  gender?: string
  phone?: string
  bio?: string
  // 注意：不包含avatar字段，因为头像通过单独的接口上传
}
// 移除未使用的接口定义

/**
 * 获取用户信息
 */
export const getUserInfo = () => {
  console.log('[API] getUserInfo - 发送请求')
  return request({
    url: '/xiangsu/user/profile/',
    method: 'get'
  }).then(response => {
    console.log('[API] getUserInfo - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getUserInfo - 请求失败', error)
    throw error
  })
}

/**
 * 更新用户信息
 */
export const updateUserInfo = (data: UpdateUserInfoData) => {
  console.log('[API] updateUserInfo - 发送请求', data)
  return request({
    url: '/xiangsu/user/profile/',
    method: 'put',
    data
  }).then(response => {
    console.log('[API] updateUserInfo - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] updateUserInfo - 请求失败', error)
    throw error
  })
}

/**
 * 获取用户积分
 */
export const getUserPoints = () => {
  console.log('[API] getUserPoints - 发送请求')
  return request({
    url: '/xiangsu/user/points/',
    method: 'get'
  }).then(response => {
    console.log('[API] getUserPoints - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getUserPoints - 请求失败', error)
    throw error
  })
}

/**
 * 上传头像
 */
export const uploadAvatar = (data: any) => {
  console.log('[API] uploadAvatar - 发送请求', data)
  return request({
    url: '/xiangsu/upload/avatar/',
    method: 'post',
    data
  }).then(response => {
    console.log('[API] uploadAvatar - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] uploadAvatar - 请求失败', error)
    throw error
  })
}

/**
 * 获取当前用户完整信息
 */
export const getCurrentUser = () => {
  console.log('[API] getCurrentUser - 发送请求')
  return request({
    url: '/xiangsu/current-user/',
    method: 'get'
  }).then(response => {
    console.log('[API] getCurrentUser - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getCurrentUser - 请求失败', error)
    throw error
  })
}

/**
 * 获取用户统计数据
 * 包括：发布动态数、完成挑战数、碳足迹记录数
 */
export const getUserStatistics = () => {
  console.log('[API] getUserStatistics - 发送请求')
  return request({
    url: '/xiangsu/user/statistics/',
    method: 'get'
  }).then(response => {
    console.log('[API] getUserStatistics - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getUserStatistics - 请求失败', error)
    throw error
  })
}

/**
 * 获取用户积分排行榜（碳积分）
 */
export const getUserLeaderboard = (limit: number = 10, period: 'weekly'|'monthly'|'all' = 'weekly', offset: number = 0) => {
  console.log('[API] getUserLeaderboard - 发送请求', { limit, period, offset })
  return request({
    url: '/xiangsu/user/leaderboard/',
    method: 'get',
    params: { limit, period, offset }
  }).then(response => {
    console.log('[API] getUserLeaderboard - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getUserLeaderboard - 请求失败', error)
    throw error
  })
}

export const getUserBadges = () => {
  console.log('[API] getUserBadges - 发送请求')
  return request({
    url: '/xiangsu/user/badges/',
    method: 'get'
  }).then(response => {
    console.log('[API] getUserBadges - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getUserBadges - 请求失败', error)
    throw error
  })
}

/**
 * 用户签到（后端判定是否重复与当日剩余）
 */
export const checkin = () => {
  console.log('[API] checkin - 发送请求')
  return request({
    url: '/xiangsu/user/checkin/',
    method: 'post'
  }).then(response => {
    console.log('[API] checkin - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] checkin - 请求失败', error)
    throw error
  })
}

/**
 * 获取积分交易流水
 */
export const getPointTransactions = (page: number = 1, page_size: number = 10) => {
  console.log('[API] getPointTransactions - 发送请求', { page, page_size })
  return request({
    url: '/xiangsu/rewards/transactions/',
    method: 'get',
    params: { page, page_size }
  }).then(response => {
    console.log('[API] getPointTransactions - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getPointTransactions - 请求失败', error)
    throw error
  })
}

/**
 * 获取每日任务列表
 */
export const getDailyTasks = () => {
  console.log('[API] getDailyTasks - 发送请求')
  const today = new Date()
  const dateStr = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,'0')}-${String(today.getDate()).padStart(2,'0')}`
  const cfg = getTasksEndpointsConfig()
  const configuredAttempt = cfg.daily ? [{ url: String(cfg.daily), method: 'get' as const }] : []
  return requestFirstSuccess([
    ...configuredAttempt,
    { url: '/xiangsu/tasks/daily/', method: 'get' },
    { url: '/xiangsu/tasks/daily', method: 'get' },
    { url: '/xiangsu/user/tasks/daily/', method: 'get' },
    { url: '/xiangsu/user/tasks/today/', method: 'get' },
    { url: '/xiangsu/tasks/today/', method: 'get' },
    { url: '/xiangsu/daily-tasks/', method: 'get' },
    { url: '/xiangsu/tasks/', method: 'get', params: { date: dateStr, scope: 'daily' } },
    { url: '/xiangsu/user/tasks/', method: 'get', params: { date: dateStr } }
  ])
  .then(response => {
    console.log('[API] getDailyTasks - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getDailyTasks - 请求失败', error)
    throw error
  })
}

/**
 * 完成任务
 */
export const completeTask = (taskId: number) => {
  console.log('[API] completeTask - 发送请求', taskId)
  const cfg = getTasksEndpointsConfig()
  const configured = cfg.complete && typeof cfg.complete === 'string' ? String(cfg.complete) : ''
  const configuredAttempt = configured ? [{ url: configured.replace('{id}', String(taskId)), method: 'post' as const }] : []
  return requestFirstSuccess([
    ...configuredAttempt,
    { url: `/xiangsu/tasks/${taskId}/complete/`, method: 'post' },
    { url: `/xiangsu/tasks/${taskId}/complete`, method: 'post' },
    { url: `/xiangsu/user/tasks/${taskId}/complete/`, method: 'post' },
    { url: '/xiangsu/tasks/complete/', method: 'post', data: { id: taskId } },
    { url: '/xiangsu/user/tasks/complete/', method: 'post', data: { id: taskId } },
    { url: `/xiangsu/tasks/${taskId}/finish/`, method: 'post' },
    { url: `/xiangsu/tasks/${taskId}/`, method: 'patch', data: { status: 'completed' } },
    { url: `/xiangsu/user/tasks/${taskId}/`, method: 'patch', data: { status: 'completed' } },
    { url: `/xiangsu/tasks/${taskId}/status/`, method: 'put', data: { status: 'completed' } }
  ])
  .then(response => {
    console.log('[API] completeTask - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] completeTask - 请求失败', error)
    throw error
  })
}

/**
 * 获取首页轮播图配置
 */
export const getHomeBanners = () => {
  console.log('[API] getHomeBanners - 发送请求')
  return request({
    url: '/xiangsu/banners/',
    method: 'get'
  }).then(response => {
    console.log('[API] getHomeBanners - 响应成功', response)
    return response
  }).catch(error => {
    console.error('[API] getHomeBanners - 请求失败', error)
    throw error
  })
}

export const listAdminTasks = (params?: any) => {
  return requestFirstSuccess([
    { url: '/xiangsu/admin/tasks/', method: 'get', params },
    { url: '/xiangsu/tasks/admin/', method: 'get', params },
    { url: '/xiangsu/tasks/manage/', method: 'get', params }
  ])
}

export const createAdminTask = (data: any) => {
  return requestFirstSuccess([
    { url: '/xiangsu/admin/tasks/', method: 'post', data },
    { url: '/xiangsu/tasks/admin/', method: 'post', data },
    { url: '/xiangsu/tasks/manage/', method: 'post', data }
  ])
}

export const updateAdminTask = (id: number, data: any) => {
  return requestFirstSuccess([
    { url: `/xiangsu/admin/tasks/${id}/`, method: 'patch', data },
    { url: `/xiangsu/tasks/admin/${id}/`, method: 'patch', data },
    { url: `/xiangsu/tasks/manage/${id}/`, method: 'patch', data }
  ])
}

export const deleteAdminTask = (id: number) => {
  return requestFirstSuccess([
    { url: `/xiangsu/admin/tasks/${id}/`, method: 'delete' },
    { url: `/xiangsu/tasks/admin/${id}/`, method: 'delete' },
    { url: `/xiangsu/tasks/manage/${id}/`, method: 'delete' }
  ])
}

export const publishDailyTasks = (data: { date: string; task_ids?: number[] }) => {
  return requestFirstSuccess([
    { url: '/xiangsu/admin/tasks/publish/', method: 'post', data },
    { url: '/xiangsu/tasks/admin/publish/', method: 'post', data },
    { url: '/xiangsu/tasks/publish/', method: 'post', data }
  ])
}
